import { Button, Cascader, Modal } from 'antd';
import FormRender, { useForm } from 'form-render';
import { connect } from 'umi';

import { useDispatch, useSelector } from '@umijs/max';

const EditForm = (props) => {
  const dispatch = useDispatch();
  const { actionRef } = props;
  const { addOpen, drawerType, loading, drawerParams } = useSelector((state) => state.groupManageApproval);

  const form = useForm();

  const update = (data) => {
    dispatch({
      type: 'groupManageApproval/updateState',
      payload: data,
    });
  };

  const schema = {
    type: 'object',
    properties: {
      refusal: {
        title: '原因',
        type: 'string',
        max: 20,
        widget: 'textArea',
        props: {
          row: 4,
        },
      },
    },
  };

  const onFinish = (data) => {
    const { ...others } = data;
    let searchParams = {
      ...others,
      id: drawerParams.id,
    };
    if (drawerType === 'unAgree') {
      dispatch({
        type: 'groupManageApproval/getCategoryRepulse',
        payload: { ...searchParams, actionRef },
      });
    }
  };

  const watch = {
    parr: (val) => {
      if (val) {
        if (val.length === 1 && val[0] === '0') {
          form.setFields([{ name: 'level', value: 1 }]);
        } else if (val.length > 0) {
          form.setFields([{ name: 'level', value: val.length + 1 }]);
        }
      }
    },
    level: (val) => {
      if (val === 3) {
        form.setFields([{ name: 'status', value: 1 }]);
      }
    },
  };

  return (
    <Modal
      title="驳回"
      open={addOpen}
      destroyOnClose
      onCancel={() => {
        form.resetFields();
        update({ addOpen: false, drawerParams: {}, drawerType: '' });
      }}
      footer={
        <>
          <Button type="primary" loading={loading} onClick={form.submit}>
            确认
          </Button>
          <Button onClick={() => update({ addOpen: false })}>取消</Button>
        </>
      }
    >
      <FormRender
        widgets={{ cascader: Cascader }}
        form={form}
        watch={watch}
        schema={schema}
        onFinish={onFinish}
      />
    </Modal>
  );
};

export default connect(({ groupManageApproval, loading }) => {
  return {
    groupManageApproval,
    loading: loading.effects['groupManageApproval/selectPage'],
  };
})(EditForm);
